package com.example.maybeaccount;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.maybeaccount.Entry.Entrance;
import com.example.maybeaccount.Mode.ClassifyManager;
import com.example.maybeaccount.Mode.DetailsMarkerView;
import com.example.maybeaccount.Mode.Item;
import com.example.maybeaccount.Mode.ItemAdapter;
import com.example.maybeaccount.Mode.ItemManager;
import com.example.maybeaccount.Mode.MemberItemAdapter;
import com.example.maybeaccount.Mode.MyPercentFormatter;
import com.example.maybeaccount.Mode.MyTimer;
import com.example.maybeaccount.Mode.SpacesItemDecoration;
import com.example.maybeaccount.Mode.SqliteDB;
import com.example.maybeaccount.datepicker.CustomDatePicker;
import com.example.maybeaccount.datepicker.DateFormatUtils;
import com.example.maybeaccount.multiselectpopupwindows.model.Search;
import com.example.maybeaccount.multiselectpopupwindows.widget.MultiSelectPopupWindows;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
//import com.github.mikephil.charting.formatter.MyPercentFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 展示二级饼图和对应一级的所有账单
 * 注：有的一级分类无二级
 */
public class ChartClass2Activity extends AppCompatActivity {

    private boolean isTop;
    private int firstFlag = 0;
    private Calendar startCalendar;
    private Calendar endCalendar;
    private ArrayList<String> class2NameList;
    private ItemManager itemManager;
    private List<Search> itemlists = new ArrayList<>();
    private int mode;
    private String class1Name;
    private RecyclerView recyclerView;
    private TextView textClass1Name;
    private PieChart mPieChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        setContentView(R.layout.activity_chart_class2);

        /** 获取mode、一级分类名、开始时间、结束时间 */
        if(savedInstanceState != null){
            startCalendar = (Calendar) savedInstanceState.getSerializable("startTime");
            endCalendar = (Calendar) savedInstanceState.getSerializable("endTime");
            mode = savedInstanceState.getInt("mode",3);
            class1Name = savedInstanceState.getString("nameClass1");
        }else{
            Intent intent = getIntent();
            startCalendar = (Calendar) intent.getSerializableExtra("startTime");
            endCalendar = (Calendar) intent.getSerializableExtra("endTime");
            mode = intent.getIntExtra("mode",3);
            class1Name = intent.getStringExtra("nameClass1");
        }

        /** 获取布局 */
        mPieChart = (PieChart) findViewById(R.id.mPieChart);
        recyclerView = findViewById(R.id.recycler_view);
        textClass1Name = findViewById(R.id.class1_name);

        textClass1Name.setText(class1Name+"类");

        //获取itemManager
        //itemManager = (ItemManager)getIntent().getSerializableExtra("itemManager");
        itemManager = new ItemManager();
        ArrayList<Item> itemArrayList = new ArrayList<Item>();
        itemArrayList = SqliteDB.getInstance(getApplicationContext()).getAllItem();
        if(itemArrayList.size() != 0){
            itemManager.setItem(itemArrayList);
        }
        itemManager.chooseAccount("全部账户");


        ActionBar actionbar=getSupportActionBar();
        if(actionbar!=null){
            actionbar.hide();
        }

        setRecyclerView(mode);
        initPieChart(mode);
        mPieChart.setVisibility(View.VISIBLE);
        mPieChart.setNoDataText("请先选择要显示的内容");

        //返回按钮
        ImageButton butChartBack = (ImageButton)findViewById(R.id.button_chart_back);
        butChartBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent= new Intent(ChartClass2Activity.this, Chart.class);
                //intent.putExtra("member",1);
                //startActivity(intent);
                finish();
            }
        });


    }

    /** 保存 */
    @Override
    protected void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putSerializable("startTime",startCalendar);
        outState.putSerializable("endTime",endCalendar);
        outState.putInt("mode",mode);
        outState.putString("nameClass1",class1Name);

    }

    /**
     * 重写返回键
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            //Intent intent = new Intent(this, Chart.class);
            //intent.putExtra("member",1);
            //startActivity(intent);
            finish();
        }
        return true;
    }

    /**
     * 后台唤醒后进入密码界面
     */
    @Override
    protected void onResume(){
        super.onResume();
        isTop = true;
        //int memberFlag = getIntent().getIntExtra("upActivity",0);
        if(firstFlag == 1){
            firstFlag = 0;
            Intent intent = new Intent(ChartClass2Activity.this, Entrance.class);
            intent.putExtra("resume","ChartClass2Activity");
            startActivity(intent);
        }else{
            firstFlag = 0;
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        isTop = false;
    }

    /**
     *
     * @param
     */
    /*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode == RESULT_OK && resultCode == 1){
            int fromUp = data.getIntExtra("upActivity",0);
            firstFlag = 0;
        }
    }*/

    private void initPieChart(int mode){

        mPieChart.setUsePercentValues(true);
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(5, 10, 5, 5);
        //标签字体颜色
        mPieChart.setEntryLabelColor(Color.WHITE);
        mPieChart.setEntryLabelTextSize(15f);

        Legend legend = mPieChart.getLegend();
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setTextSize(12f);
        legend.setFormSize(12f);
        legend.setFormToTextSpace(5f);

//        ArrayList<PieEntry> entryList = new ArrayList<>();
//        entryList.add(new PieEntry(30f, "交通"));
//        entryList.add(new PieEntry(30f, "购物"));
//        entryList.add(new PieEntry(40f, "餐饮"));


        final List<PieEntry> entryList = this.getPieEntryList(mode);
        PieDataSet dataSet = new PieDataSet(entryList,"");
        //add color
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.MATERIAL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.JOYFUL_COLORS) {
            colors.add(c);
        }

        dataSet.setColors(colors);
        dataSet.setDrawIcons(false);
        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);
        //显式格式为百分比
        dataSet.setValueFormatter(new PercentFormatter());

        //** 设置显示数据的属性
        PieData pieData = new PieData(dataSet);
        //pieData.setDrawValues(true);
        pieData.setValueFormatter(new MyPercentFormatter(mPieChart));
        pieData.setValueTextSize(15f);
        pieData.setValueTypeface(Typeface.DEFAULT_BOLD);
        pieData.setValueTextColor(Color.WHITE);

        mPieChart.getDescription().setEnabled(false);
        mPieChart.setData(pieData);
        mPieChart.animateXY(1500,1500);
        mPieChart.invalidate();
        /** 设置点击事件 **/
        mPieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            private String targetValue;
            /** 一次点击，放大 */
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                if (e == null){return;}
                //此时e.getY()等于数据 由此判断点击了哪一个扇区
                for(int i = 0;i < entryList.size(); i++){
                    if(entryList.get(i).getValue() == e.getY()){
                        targetValue = entryList.get(i).getLabel();
                        break;
                    }
                }
            }
            /** 二次点击，显示详情 */
            @Override
            public void onNothingSelected() {
                //图表外部点击事件 也是（上一个方法为点击一次放大） 本方法为二次点击事件
                //Toast.makeText(Chart.this,"点了两次",Toast.LENGTH_LONG).show();
                /** 匹配到底是哪个分类 */
                if(targetValue != null && !targetValue.equals("")){

                }
            }
        });

    }

    /**
     * 获取饼图数据
     * @param mode 设置模式，包括支出和收入
     * @return
     */
    private List<PieEntry> getPieEntryList(int mode){
        ArrayList<String> objectList = new ArrayList<String>();
        //获取自定义内容的字符串数组
        ClassifyManager classifyManager = new ClassifyManager(this);
        classifyManager.initFromXML();
        objectList = classifyManager.getChildOfClass1(class1Name);

        ArrayList<Item> selectedItem = itemManager.getItemByTimeAndClass(objectList, ItemManager.SCREEN_MODE_CLASS2, startCalendar,endCalendar);
        ArrayList<PieEntry> entryList = new ArrayList<PieEntry>();

        if(mode == Chart.MODE_INCOME){
            for(Item item:selectedItem){
                entryList.add(new PieEntry((float) item.getIncome(),item.getClass2()));
            }
        }else if(mode == Chart.MODE_OUTCOME){
            for(Item item:selectedItem){
                entryList.add(new PieEntry((float) item.getExpend(),item.getClass2()));
            }
        }else{

        }

        return entryList;
    }

    private void setRecyclerView(int mode){
        if(itemManager != null){
            LinearLayoutManager layoutManager= new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);
            //设置各个item之间的间隔
            int space = 2;
            recyclerView.addItemDecoration(new SpacesItemDecoration(space));
            ItemAdapter itemAdapter = new ItemAdapter(itemManager.getAllItemByTimeAndClass1(class1Name,startCalendar,endCalendar),ItemAdapter.ALL_MODE,this);
            recyclerView.setAdapter(itemAdapter);
        }
    }

    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) && isTop) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS) && isTop) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        this.getWindow().setFlags(0x80000000,0x80000000);
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }
}


